package routes

import (
	"things_iot_backend/handlers"
	"things_iot_backend/middleware"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func SetupRoutes(router *gin.Engine, db *gorm.DB) {
	// 初始化处理器
	authHandler := handlers.NewAuthHandler(db)
	userHandler := handlers.NewUserHandler(db)
	deviceHandler := handlers.NewDeviceHandler(db)
	eventHandler := handlers.NewEventHandler(db)
	commandHandler := handlers.NewCommandHandler(db)

	// API v1 路由组
	v1 := router.Group("/api/v1")
	{
		// 认证路由
		auth := v1.Group("/auth")
		{
			auth.POST("/login", authHandler.Login)
			auth.POST("/logout", middleware.AuthMiddleware(), authHandler.Logout)
			auth.POST("/refresh", middleware.AuthMiddleware(), authHandler.RefreshToken)
			auth.GET("/profile", middleware.AuthMiddleware(), authHandler.GetProfile)
			auth.PUT("/profile", middleware.AuthMiddleware(), authHandler.UpdateProfile)
			auth.PUT("/password", middleware.AuthMiddleware(), authHandler.ChangePassword)
		}

		// 用户管理路由（仅超级管理员）
		admin := v1.Group("/admin")
		admin.Use(middleware.AuthMiddleware(), middleware.AdminMiddleware())
		{
			users := admin.Group("/users")
			{
				users.POST("", userHandler.CreateUser)
				users.GET("", userHandler.GetUsers)
				users.PUT("/:user_id", userHandler.UpdateUser)
				users.DELETE("/:user_id", userHandler.DeleteUser)
				users.POST("/:user_id/reset-password", userHandler.ResetUserPassword)
			}
		}

		// 设备管理路由
		devices := v1.Group("/devices")
		devices.Use(middleware.AuthMiddleware())
		{
			devices.POST("", deviceHandler.CreateDevice)
			devices.GET("", deviceHandler.GetDevices)

			// 单个设备操作
			device := devices.Group("/:device_id")
			{
				device.GET("", deviceHandler.GetDevice)
				device.PUT("", deviceHandler.UpdateDevice)
				device.DELETE("", deviceHandler.DeleteDevice)

				// 设备数据
				telemetry := device.Group("/telemetry")
				{
					telemetry.GET("/latest", deviceHandler.GetDeviceTelemetryLatest)
					telemetry.GET("/history", deviceHandler.GetDeviceTelemetryHistory)
				}

				// 设备事件
				events := device.Group("/events")
				{
					events.GET("", eventHandler.GetDeviceEvents)
					events.GET("/stats", eventHandler.GetDeviceEventStats)
				}

				// 设备命令
				command := device.Group("/command")
				{
					command.POST("", commandHandler.SendCommand)
					command.GET("/queue", commandHandler.GetQueuedCommands)
					command.DELETE("/queue", commandHandler.ClearQueuedCommands)
				}

				// 子设备命令（网关设备）
				subdevices := device.Group("/subdevices")
				{
					subdevices.POST("/:subdevice_id/command", commandHandler.SendCommandToSubdevice)
				}
			}
		}

		// 系统状态路由
		system := v1.Group("/system")
		system.Use(middleware.AuthMiddleware())
		{
			system.GET("/health", func(c *gin.Context) {
				c.JSON(200, gin.H{
					"code":    200,
					"message": "系统运行正常",
					"data": gin.H{
						"status":    "healthy",
						"timestamp": time.Now().Format(time.RFC3339),
					},
				})
			})

			system.GET("/stats", func(c *gin.Context) {
				// 获取系统统计信息
				// 在实际实现中，您可能需要查询数据库获取统计信息
				c.JSON(200, gin.H{
					"code":    200,
					"message": "success",
					"data": gin.H{
						"total_users":    0,
						"total_devices":  0,
						"online_devices": 0,
						"timestamp":      time.Now().Format(time.RFC3339),
					},
				})
			})
		}
	}

	// 根路由
	router.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"code":    200,
			"message": "Things IoT Platform API",
			"data": gin.H{
				"name":    "Things IoT Platform",
				"version": "1.0.0",
				"docs":    "/api/v1/docs",
			},
		})
	})

	// 健康检查路由
	router.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status": "ok",
		})
	})

	// 404 处理
	router.NoRoute(func(c *gin.Context) {
		c.JSON(404, gin.H{
			"code":    404,
			"message": "接口不存在",
			"data":    nil,
		})
	})
}

// SetupSwagger 设置Swagger文档（可选）
func SetupSwagger(router *gin.Engine) {
	// 在实际实现中，您可以使用swaggo/gin-swagger等库
	// 这里简化处理
	router.GET("/api/v1/docs", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"code":    200,
			"message": "API文档",
			"data": gin.H{
				"swagger": "2.0",
				"info": gin.H{
					"title":   "Things IoT Platform API",
					"version": "1.0.0",
				},
				"basePath": "/api/v1",
				"schemes":  []string{"http", "https"},
			},
		})
	})
}
